package com.techsun.lf.manager;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.techsun.lf.constant.Constant;
import com.tencent.shadow.core.common.Logger;
import com.tencent.shadow.core.common.LoggerFactory;
import com.tencent.shadow.core.manager.installplugin.InstalledPlugin;
import com.tencent.shadow.dynamic.host.EnterCallback;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SamplePluginManager extends FastPluginManager {
   private static final Logger logger = LoggerFactory.getLogger(SamplePluginManager.class);

   private ExecutorService executorService = Executors.newSingleThreadExecutor();

   private Context mCurrentContext;

   public SamplePluginManager(Context context) {
      super(context);
      mCurrentContext = context;
   }

   /**
    * @return PluginManager实现的别名，用于区分不同PluginManager实现的数据存储路径
    */
   @Override
   protected String getName() {
      return "test-dynamic-manager";
   }

   /**
    * @return 宿主中注册的PluginProcessService实现的类名
    */
   @Override
   protected String getPluginProcessServiceName(String partKey) {
      if (Constant.PART_KEY_PLUGIN_USER.equals(partKey)) {
         return "com.techsun.lf.shadow.UserPluginProcessService";
      } else if (Constant.PART_KEY_PLUGIN_BASE.equals(partKey)) {
         return "com.techsun.lf.shadow.MainPluginProcessService";
      }
      throw new RuntimeException("partKey is unknown");
   }

   @Override
   public void enter(final Context context, long fromId, Bundle bundle, final EnterCallback callback) {
      if (fromId == Constant.FROM_ID_NOOP) {
         //do nothing.
      } else if (fromId == Constant.FROM_ID_START_ACTIVITY) {
         onStartActivity(context, bundle, callback);
      } else if (fromId == Constant.FROM_ID_CLOSE) {
         close();
      } else if (fromId == Constant.FROM_ID_LOAD_VIEW_TO_HOST) {
         loadViewToHost(context, bundle);
      } else {
         throw new IllegalArgumentException("不认识的fromId==" + fromId);
      }
   }

   private void loadViewToHost(final Context context, Bundle bundle) {
      Intent pluginIntent = new Intent();
      pluginIntent.setClassName(
              context.getPackageName(),
              "com.tencent.shadow.sample.plugin.app.lib.usecases.service.HostAddPluginViewService"
      );
      pluginIntent.putExtras(bundle);
      try {
         mPluginLoader.startPluginService(pluginIntent);
      } catch (RemoteException e) {
         throw new RuntimeException(e);
      }
   }

   private void onStartActivity(final Context context, Bundle bundle, final EnterCallback callback) {
      final String pluginZipPath = bundle.getString(Constant.KEY_PLUGIN_ZIP_PATH);
      final String partKey = bundle.getString(Constant.KEY_PLUGIN_NAME);
      final String className = bundle.getString(Constant.KEY_ACTIVITY_CLASSNAME);
      logger.debug("pluginZipPath:"+pluginZipPath);
      logger.debug("className:"+className);
      if (className == null) {
         throw new NullPointerException("className == null");
      }
      final Bundle extras = bundle.getBundle(Constant.KEY_EXTRAS);

      if (callback != null) {
         final View view = LayoutInflater.from(mCurrentContext).inflate(R.layout.activity_load_plugin, null);
         callback.onShowLoadingView(view);
      }

      executorService.execute(() -> {
         try {
            /**
             * 1. 安装插件统一在需要安装插件的地方进行（比如：从后台获取到新版本插件升级，或者用户手动安装时）
             * 2. 这里只根据插件名直接从数据库获取uuid进行加载即可
             * */
            Log.d("lllllll", "onStartActivity 1: ");
            InstalledPlugin installedPlugin = installPlugin(pluginZipPath, null, true);

            Log.d("lllllll", "onStartActivity 2: ");
            loadPlugin(installedPlugin.UUID, partKey);
            Log.d("lllllll", "onStartActivity 3: ");
            callApplicationOnCreate(partKey);
            Log.d("lllllll", "onStartActivity 4: ");


//            loadPlugin(installedPlugin.UUID, Constant.PART_KEY_PLUGIN_BASE);
//            loadPlugin(installedPlugin.UUID, Constant.PART_KEY_PLUGIN_USER);
//            callApplicationOnCreate(Constant.PART_KEY_PLUGIN_BASE);
//            callApplicationOnCreate(Constant.PART_KEY_PLUGIN_USER);
            Intent pluginIntent = new Intent();
            pluginIntent.setClassName(
                    context.getPackageName(),
                    className
            );
            if (extras != null) {
               pluginIntent.replaceExtras(extras);
            }
            Intent intent = mPluginLoader.convertActivityIntent(pluginIntent);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mPluginLoader.startActivityInPluginProcess(intent);
         } catch (Exception e) {
            throw new RuntimeException(e);
         }
         if (callback != null) {
            callback.onCloseLoadingView();
         }
      });
   }
}